import { DataTypes, Model, Optional } from 'sequelize';
import sequelize from '../utils/database';

// 定义OrderItem属性接口
export interface OrderItemAttributes {
  id: number;
  orderId: number;
  productId: number;
  skuId?: number;
  productName: string;
  productImage?: string;
  skuSpecifications?: object;
  price: number;
  quantity: number;
  totalAmount: number;
  createdAt?: Date;
  updatedAt?: Date;
}

// 定义创建时可选的属性
interface OrderItemCreationAttributes extends Optional<OrderItemAttributes, 'id' | 'createdAt' | 'updatedAt'> {}

// 定义OrderItem模型类
export class OrderItem extends Model<OrderItemAttributes, OrderItemCreationAttributes> implements OrderItemAttributes {
  public id!: number;
  public orderId!: number;
  public productId!: number;
  public skuId?: number;
  public productName!: string;
  public productImage?: string;
  public skuSpecifications?: object;
  public price!: number;
  public quantity!: number;
  public totalAmount!: number;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

// 初始化模型
OrderItem.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      comment: '订单商品项ID'
    },
    orderId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '订单ID',
      field: 'order_id'
    },
    productId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '商品ID',
      field: 'product_id'
    },
    skuId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: 'SKU ID',
      field: 'sku_id'
    },
    productName: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '商品名称',
      field: 'product_name'
    },
    productImage: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '商品图片',
      field: 'product_image'
    },
    skuSpecifications: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: 'SKU规格信息',
      field: 'sku_specifications'
    },
    price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '商品单价',
      field: 'price'
    },
    quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '购买数量',
      field: 'quantity'
    },
    totalAmount: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      comment: '小计金额',
      field: 'total_amount'
    }
  },
  {
    sequelize,
    tableName: 'order_items',
    modelName: 'OrderItem',
    timestamps: true,
    underscored: true,
    comment: '订单商品项表',
    indexes: [
      {
        name: 'idx_order_id',
        fields: ['order_id']
      },
      {
        name: 'idx_product_id',
        fields: ['product_id']
      },
      {
        name: 'idx_sku_id',
        fields: ['sku_id']
      }
    ]
  }
);

export default OrderItem;